<template>
  <div class="user-management-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>新增用户
      </el-button>
    </div>

    <!-- 搜索过滤 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户类型">
          <el-select v-model="searchForm.userType"
                     clearable
                     style="width: 120px"
                     placeholder="全部" >
            <el-option
                v-for="item in userTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input
              v-model="searchForm.userPhone"
              placeholder="请输入手机号"
              clearable
          />
        </el-form-item>

        <el-form-item label="姓名">
          <el-input
              v-model="searchForm.userName"
              placeholder="请输入老人姓名"
              clearable
          />
        </el-form-item>

        <el-form-item label="监护人姓名">
          <el-input
              v-model="searchForm.emergencyContact"
              placeholder="请输入监护人姓名"
              clearable
          />
        </el-form-item>

        <el-form-item label="监护人手机号">
          <el-input
              v-model="searchForm.emergencyPhone"
              placeholder="请输入手机号"
              clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-container">
      <el-table
          :data="userList"
          border
          stripe
          v-loading="loading"
          style="width: 100%"
      >
        <el-table-column prop="userName" label="姓名" width="120" />
        <el-table-column prop="userPhone" label="手机号" width="150" />
        <el-table-column prop="birthday" label="生日" width="120" />
        <el-table-column prop="address" label="地址"  width="200"/>
        <el-table-column prop="idCard" label="身份证号" width="180"/>
        <el-table-column prop="sex" label="性别" width="100" >
          <template #default="{ row }">
            {{ row.sex === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="emergencyContact" label="监护人" width="150" />
        <el-table-column prop="emergencyPhone" label="监护人电话" width="150" />
        <el-table-column prop="emergencyRelation" label="监护人与用户关系" width="150"/>
        <el-table-column prop="userType" label="用户类型" width="120">
          <template #default="{ row }">
            <el-tag :type="userTypeTagMap[row.userType]">
              {{ userTypeMap[row.userType] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            {{ userTypeList[row.status]}}
          </template>
        </el-table-column>
        <el-table-column prop="userAuth" label="权限">
          <template #default="{ row }">
            {{ userRoleOptions.find(item => item.value == row.userAuth)?.label || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleRead( row )">查看</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            <el-button type="warning" v-show="row.userType == 2" link @click="handleAuth(row)">权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="resetForm"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="140px"
      >
        <el-form-item label="姓名" prop="userName">
          <el-input :disabled="dialogValue === 'read'" v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="手机号" prop="userPhone">
          <el-input :disabled="dialogValue === 'read'" v-model="form.userPhone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker :disabled="dialogValue === 'read'"
              v-model="form.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input :disabled="dialogValue === 'read'" v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input :disabled="dialogValue === 'read'" v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select :disabled="dialogValue === 'read'" v-model="form.sex" placeholder="请选择性别">
            <el-option :value="1" label="男" :key="1"/>
            <el-option :value="2" label="女" :key="2"/>
          </el-select>
        </el-form-item>

        <el-form-item label="用户类型" prop="userType">
          <el-select :disabled="dialogValue === 'read'"
              v-model="form.userType"
              placeholder="请选择用户类型"
              style="width: 100%"
              @change="handleUserTypeChange"
          >
            <el-option
                v-for="item in userTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select :disabled="dialogValue === 'read'" v-model="form.status" placeholder="请选择状态" >
            <el-option v-for="item in processedTypeOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="监护人" prop="emergencyContact">
          <el-input :disabled="dialogValue === 'read'" v-model="form.emergencyContact" placeholder="请输入监护人姓名"/>
        </el-form-item>
        <el-form-item label="监护人电话" prop="emergencyPhone">
          <el-input :disabled="dialogValue === 'read'" v-model="form.emergencyPhone" placeholder="请输入监护人电话"/>
        </el-form-item>
        <el-form-item label="监护人与用户关系" prop="emergencyRelation">
          <el-input :disabled="dialogValue === 'read'" v-model="form.emergencyRelation" placeholder="请输入监护人与用户关系"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog
        title="分配权限"
        v-model="dialogRole"
        width="500px"
        @close="resetForm">
      <el-select v-model="form.userAuth" placeholder="请选择权限" clearable>
        <el-option v-for="item in userRoleOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <template #footer>
        <el-button @click="dialogRole = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { get, post, put, del } from '@/utils/request'

// 类型定义
interface User {
  id?: number
  userName: string
  userPhone: string
  userType: number
  status: number
  birthday?: string
  sex: number,
  emergencyContact: string
  emergencyRelation: string
  emergencyPhone: string
  createTime?: string
  userAuth: string
}

// 用户类型映射
const userTypeMap: Record<number, string> = {
  1: '老人',
  2: '工作人员'
}
const userTypeList: Record<number, String> = {
  1: '在世',
  2: '离世',
  3: '在职',
  4: '离职',
  5: '冻结'
}
const userTypeTagMap: Record<number, string> = {
  0: 'danger',
  1: 'success',
  2: 'warning'
}

// 搜索表单
const searchForm = reactive({
  userType: null,
  userPhone: '',
  userName: '',
  emergencyContact:'',
  emergencyPhone: ''
})

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const userList = ref<User[]>([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogRole = ref(false)
const formRef = ref<FormInstance>()
const dialogTitle = computed(() => form.id ? '编辑用户' : '新增用户')

// 表单数据
const form = reactive<User>({
  id:null,
  userName: '',
  userPhone: '',
  birthday: '',
  address: '',
  sex: 1,
  userType: null,
  status: null,
  idCard: '',
  emergencyContact: '',
  emergencyRelation: '',
  emergencyPhone: ''
})

// 验证规则
const rules = reactive({
  userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  userPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  idCard: [{required: true, message: '请输入身份证号', trigger: 'blur'},
    {
      pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
      message: '身份证号格式不正确',
      trigger: 'blur'
    }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
})

// 用户类型选项
const userTypeOptions = ref([
  { value: 1, label: '老人' },
  { value: 2, label: '工作人员' }
])

const userRoleOptions = ref([
  {value: '2', label: '管理员'},
  {value: '1',label: '服务人员'}
])

interface SelectOption {
  value: number
  label: string
}

// 提前定义配置项
const USER_TYPE_OPTIONS: Record<number, SelectOption[]> = {
  1: [
    { value: 1, label: '在世' },
    { value: 2, label: '离世' }
  ],
  2: [
    { value: 3, label: '在职' },
    { value: 4, label: '离职' },
    { value: 5, label: '冻结' }
  ]
}

// 使用ref声明响应式数据
const processedTypeOptions = ref<SelectOption[]>([])
// 初始化数据
onMounted(() => {
  fetchUsers()
})

const handleUserTypeChange = () =>{
  console.log(form.userType)
  form.status = null
  processedTypeOptions.value = USER_TYPE_OPTIONS[form.userType] || []
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.size
    }

    const res = await get('/user/page', params)
    userList.value = res.records
    pagination.total = res.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    userType: null,
    phone: '',
    userName: '',
    emergencyContact:'',
    emergencyPhone: ''
  })
  handleSearch()
}

// 打开新建对话框
const handleCreate = () => {
  dialogVisible.value = true
}

const dialogValue = ref('')
// 打开编辑对话框
const handleEdit = (row: User) => {
  dialogValue.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}
const handleRead = (row: User) => {
  dialogValue.value = 'read'
  Object.assign(form,row)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if(!dialogRole){
    if (!formRef.value) return
    await formRef.value.validate()
  }


  try {


    const api = form.id ? put : post
    const url = form.id ? '/user/update' : '/user/insert'

    await api(url, form)
    ElMessage.success(form.id ? '修改成功' : '新增成功')
    dialogVisible.value = false
    dialogRole.value = false
    fetchUsers()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 删除用户
const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm(`确定删除用户 ${row.userName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await del(`/user/${row.id}`)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    console.log('取消删除')
  }
}
const handleAuth = async (row: User) => {
  dialogRole.value = true
  Object.assign(form,row)
}


// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id:null,
    userName: '',
    userPhone: '',
    birthday: '',
    address: '',
    sex: 1,
    userType: null,
    status: null,
    idCard: '',
    emergencyContact: '',
    emergencyRelation: '',
    emergencyPhone: ''
  })
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchUsers()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  fetchUsers()
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
